package com.linked.universal.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.linked.universal.common.LinkedToken;
import com.linked.universal.linkedutil.HashUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Bluerain
 * @version 1.0
 * @data 2025/1/10 14:11
 * @describe todo
 */
public class LinkedCurrentUser {

    private final static Logger logger = LoggerFactory.getLogger(LinkedCurrentUser.class);

    public static String getUserId() throws Exception {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String tokenStr = request.getHeader("Authentication");
        if (StringUtils.isEmpty(tokenStr)) {
            logger.warn("header未传入Token!");
            return null;
        }
        byte[] token_bytes = HashUtil.decryptBASE64(tokenStr);
        ObjectMapper mapper = new ObjectMapper();
        LinkedToken linkedToken = mapper.readValue(token_bytes, LinkedToken.class);
        return linkedToken.getUserId();
    }

}
